<?php
class PortalWebServiceServer extends WebServiceServer {
	private $timeless;
	private $time_now;
	private $time_shift;
	private $config;

	const CONFIG_FILE = '/data/mytvplus/portal_service/conf/server.xml';

	public function __construct($config, $timeless, $time_now, $time_shift) {
		parent::__construct($config->key, $config->version);
		$network_list = array(
			'202.126.48.0/20',
			'10.1.0.0/16'
		);

		$client_ip = (isset($_SERVER['HTTP_X_FORWARDED_FOR']) &&$_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] :$_SERVER['REMOTE_ADDR'];
		if (!self::isGoodIp($client_ip, $network_list)) {
			$this->timeless = FALSE;
			$this->time_now = time();
			$this->time_shift = FALSE;
		} else {
			$this->timeless = $timeless;
			$this->time_now = $time_now;
			$this->time_shift = $time_shift;
		}
		$this->config = $config;
	}

	public function isGoodIp($ip, array $network_list) {
		$ip = ip2long($ip);
		foreach ($network_list as $network) {
			list($ip_part, $masked_bits) = explode('/', $network);
			$free_bits = 32 - $masked_bits;
			$mask = intval(str_pad('', $masked_bits, '1'),2) << $free_bits;
			$ip_head = ip2long($ip_part) & $mask;

			$ip_from = $ip_head | intval(str_pad('', $free_bits, '0'), 2);
			$ip_to = $ip_head | intval(str_pad('', $free_bits, '1'), 2);

			if ( ($ip >= $ip_from) && ($ip <= $ip_to)) {
				return true;
			}
		}
		return false;
	}

	protected function handleRequest($method_name, $parameters, $files) {
		$service = new PortalWebService($this->config, $this->timeless, $this->time_now, $this->time_shift);
		return call_user_func_array(array($service, $method_name), $parameters);
	}
}
?>
